#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>
#include <string>
#include <iomanip>
#include <cblas.h>
#include <lapacke.h>
#include "Spline.hpp"
#include "Curvefitting.hpp"
#define PI 3.14159265358979323846

class Fx : public Function {
public:
    double operator() (double t) const override {
        return 16 * pow(sin(t), 3);
    }
};

class Fy : public Function {
public:
    double operator() (double t) const override {
        return 13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t);
    }
};

void generate_and_save_fitting_equidistant(int n, const std::string &filename) {
    std::vector<double> X(n + 1);
    std::vector<double> Y(n + 1);
    std::vector<double> T(n + 1);

    Fx fx;
    Fy fy;

    // 生成心形曲线的采样点
    for (int i = 0; i <= n; ++i) {
        T[i] = static_cast<double>(i) / n; // 等距参数 t 值
        X[i] = fx(2 * PI * T[i]);
        Y[i] = fy(2 * PI * T[i]);
    }

    // 使用等距节点方法拟合
    auto result = Curve_Fitting_Equidistantnode(X, Y, T);

    // 提取拟合点并保存到文件
    const std::vector<double>& x_spline = result[0];
    const std::vector<double>& y_spline = result[1];

    std::ofstream file(filename);
    if (file.is_open()) {
        for (size_t i = 0; i < x_spline.size(); ++i) {
            file << x_spline[i] << ", " << y_spline[i] << std::endl;
        }
        file.close();
        std::cout << "Fitted spline points saved to " << filename << std::endl;
    } else {
        std::cerr << "Failed to open file " << filename << std::endl;
    }
}

int main() {
    // 使用等距节点拟合，生成 N = 10, 40, 160 的结果
    generate_and_save_fitting_equidistant(10, "E1_fitted_spline_equidistant_N10.txt");
    generate_and_save_fitting_equidistant(40, "E1_fitted_spline_equidistant_N40.txt");
    generate_and_save_fitting_equidistant(160, "E1_fitted_spline_equidistant_N160.txt");
    return 0;
}
